<template>
  <div id="panel">
    <el-row :gutter="20">
      <el-col :span="24" class="body-container">
        <el-card class="queryForm">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            label-width="150px"
          >
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="污染源">
              <ElTreeSelect
                :data="treeData"
                v-model="selectedNodeId"
                @change="handleChange"
                placeholder="请选择节点..."
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button
                icon="el-icon-refresh"
                size="mini"
                @click="handleExport"
                >导出</el-button
              >
            </el-form-item>
          </el-form>
          <div class="data-content">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5" style="float: right">
                <el-radio-group
                  v-model="viewType"
                  class="view-filter"
                  @change="handleViewChange"
                >
                  <el-radio label="table">表格</el-radio>
                  <el-radio label="chart">图表</el-radio>
                </el-radio-group>
              </el-col>
            </el-row>
            <!-- 表格视图：确保 v-if 切换时重新渲染 -->
            <div
              v-if="viewType === 'table'"
              class="table-container"
              key="table-view"
            >
              <el-table
                id="selectTable"
                :height="tableHeight"
                :data="tableData"
                border
                style="width: 100%"
              >
                <!-- <el-table-column prop="date" label="日期" width="180">
            </el-table-column> -->
                <el-table-column
                  v-for="column in tableOp"
                  :key="column.prop"
                  :prop="column.prop"
                  :label="column.label"
                  align="center"
                >
                  <template slot-scope="scope">
                    <!-- 高亮显示异常值 -->
                    <span
                      v-if="scope.row[column.prop + '_v'] == '1'"
                      style="color: red"
                      >{{ scope.row[column.prop] }}</span
                    >
                    <span v-else>{{ scope.row[column.prop] }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 图表视图：修复 DOM 渲染问题 -->
            <div
              v-else-if="viewType === 'chart'"
              class="chart-container"
              key="chart-view"
            >
              <!-- 确保容器有明确高度，避免 echarts 初始化异常 -->
              <div
                ref="chartContainer"
                style="width: 100%; height: 100%; min-height: 580px"
              ></div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
import tableToExcel from "@/utils/tableToExcel";
import ElTreeSelect from "./TreeSelect.vue";
import { formatDate } from "@/utils/ruoyi";
import {
  getPmDataTree,
  getPmDataList,
} from "@/api/dataResources/waterJcData/jcsection";
export default {
  name: "HydrologicStation",
  components: {
    ElTreeSelect,
  },
  computed: {},
  data() {
    return {
      selectedNodeId: "", // 这里仍然绑定的是ID
      selectedPid: "",
      viewType: "table", // 表格/图表视图切换（移到表单内统一管理）
      // 图表实例（保持不变）
      chartInstance: null,
      treeData: [],
      tableHeight: window.innerHeight - 280,
      radio3: "水源地类型",
      radio2: "最新",
      value1: [],
      value2: [],
      // 部门名称
      deptName: undefined,

      options: [
        { value: "河流1", label: "河流1" },
        { value: "河流2", label: "河流2" },
        { value: "河流3", label: "河流3" },
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      tableList: {
        total: 0,
        rows: [],
      },
      // 总条数
      total: 0,
      dateRange: [],
      // 选中数组
      ids: [],
      tableOp: [],
      tableData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 是否显示新增/修改弹出层
      open: false,
      // 弹出层标题
      title: "",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "用户名称长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        deptId: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  watch: {},
  created() {
    this.dateRange = this.getDefaultDateRange();
    this.getDeptTree();
  },
  mounted() {},
  methods: {
    // 视图切换处理（修复核心：增加图表销毁逻辑，避免DOM冲突）
    handleViewChange() {
      console.log(">>>视图切换为:", this.viewType);

      // 切换视图前先销毁已有图表实例，防止DOM残留
      if (this.chartInstance) {
        this.chartInstance.dispose();
        this.chartInstance = null;
      }

      // 切换为图表视图时，确保DOM渲染完成后再初始化
      if (this.viewType === "chart") {
        this.$nextTick(() => {
          // 双重保险：确保容器存在再初始化
          if (this.$refs.chartContainer) {
            this.initChart();
          }
        });
      }
    },
    //页面初始化请求的数据
    pageInit() {
      this.getList();
    },
    handleChange(info) {
      console.log("选中的ID:", info.id);
      console.log("选中的PID:", info.pid);
      console.log("完整节点信息:", info.node);

      // 保存PID
      this.selectedPid = info.pid;
      this.pageInit();
    },
    // 获取默认时间范围：[本月第一天, 当前日期]
    getDefaultDateRange() {
      const firstDay = new Date();
      firstDay.setDate(1);

      const today = new Date();

      return [formatDate(firstDay), formatDate(today)];
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      getPmDataTree().then((response) => {
        this.treeData = response.data;
        console.log(">>>这个就是树啊", response);
      });
    },

    //表格checkbox选择数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
    },

    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryParams.pageNum = val;
      this.getList();
    },
    //搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    //重置、清除表单
    resetQuery() {
      // this.dateRange = [];
      this.resetForm("queryForm");
    },
    // 弹出层取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        stationName: "",
        riverName: "",
        longitude: "",
        latitude: "",
        sex: "",
        address: "",
      };
      this.resetForm("form");
    },

    handleExport() {
      // 导出逻辑
      tableToExcel.getExcel("#selectTable", "污染源在线监测数据");
    },
    // 获取表格数据
    getList() {
      let query = {
        id: this.selectedNodeId,
        pid: this.selectedPid,
        startTime: this.dateRange.length > 0 ? this.dateRange[0] : "",
        endTime: this.dateRange.length > 0 ? this.dateRange[1] : "",
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
      };
      getPmDataList(query).then((res) => {
        console.log(">>>让我看看你", res);

        this.tableOp = res.data.tableOp;
        this.tableData = res.data.tableData;
      });
    },
    // 初始化图表（优化：增加异常处理）
    initChart() {
      try {
        // 1. 销毁已有图表实例（避免重复渲染冲突）
        if (this.chartInstance) {
          this.chartInstance.dispose();
        }

        // 2. 校验数据（无数据时不渲染）
        if (
          !this.$refs.chartContainer ||
          this.tableData.length === 0 ||
          this.tableOp.length === 0
        ) {
          return;
        }

        // 3. 初始化图表实例
        this.chartInstance = echarts.init(this.$refs.chartContainer);

        // 4. 从接口数据中提取图表所需数据
        // 排除“监测时间”列，只处理指标列
        const indicatorCols = this.tableOp.filter(
          (col) => col.prop !== "column1"
        );
        // X轴：监测时间（column1）
        const xAxisData = this.tableData.map((row) => row.column1);
        // 图例：指标列的label（如“总磷(mg/l)”）
        const legendData = indicatorCols.map((col) => col.label);
        // 系列数据：每个指标对应的数值数组
        const seriesData = indicatorCols.map((col) => ({
          name: col.label,
          type: "line",
          smooth: true,
          lineStyle: { width: 3 },
          // 提取当前指标列的数值（确保为数字类型）
          data: this.tableData.map((row) => {
            return typeof row[col.prop] === "number"
              ? row[col.prop]
              : Number(row[col.prop]) || 0;
          }),
        }));

        // 5. 图表配置项（仅渲染数据相关配置）
        const option = {
          title: {
            text: "污染源监测数据趋势",
            left: "center",
          },
          tooltip: {
            trigger: "axis",
            axisPointer: { type: "shadow" },
          },
          legend: {
            data: legendData,
            top: 30,
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: xAxisData,
            axisLabel: { rotate: 45 }, // 旋转时间标签避免重叠
          },
          yAxis: {
            type: "value",
            splitArea: { show: true },
          },
          series: seriesData,
        };

        // 6. 渲染图表
        this.chartInstance.setOption(option);

        // 7. 窗口 resize 适配
        window.addEventListener("resize", () => {
          this.chartInstance.resize();
        });
      } catch (error) {
        console.error("图表渲染失败:", error);
        this.$message.error("图表加载失败，请重试");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
}

img {
  vertical-align: middle;
}

#panel {
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;

  // 控制分页的样式----二次开发
  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
    position: relative;

    .el-pagination__total {
      position: absolute;
      left: 5px;
      color: #409eff;
      font-weight: 600;
      font-size: 15px;
    }
  }

  // 控制分页刷新按钮样式
  .refresh-button {
    .el-icon-refresh {
      font-size: 18px;
      line-height: 28px;
    }
  }

  .el-card {
    margin: 10px;
  }

  .queryForm .el-card__body {
    padding: 0 20px !important;
  }

  .queryForm {
    // .el-card__body {
    //   padding-left: 0 !important;
    // }
    .el-form-item {
      margin: 20px 0 20px 20px;
    }

    .el-form-item:first-child {
      margin-left: 0 !important;
    }

    .el-form-item__label {
      padding-right: 5px;
      color: #555;
    }

    .times {
      .el-form-item__content {
        width: 250px;
      }
    }

    .el-form-item__content {
      min-width: 200px;
      // & > div {
      //   width: 100% !important;
      // }
    }

    .searchBtnBox {
      display: inline-block;
      margin: 20px 0 20px 20px;
    }
  }

  .pageContent {
    .tabs-list {
      padding-top: 20px;
    }

    .el-tabs__header {
      background: #fff;
    }

    .el-tabs__item {
      border: 1px solid #eee;
      margin: 0;
      border-left: 0;
      background: #fafbfc;
      color: #000;
    }

    .el-tabs__item:first-child {
      margin-left: 20px;
      border-left: 1px solid #eee;
    }

    .is-active {
      border-bottom: 0 !important;
      background: #fff;
      color: #307eff;
    }
  }

  .anjian label {
    padding: 0 !important;
    width: 100px !important;
  }

  .queryForm .el-checkbox {
    margin-right: 10px !important;
    width: auto !important;
  }

  .iszgfc .el-form-item__content {
    width: 120px;
  }
}
</style>
